<?php
/**
 * Created by PhpStorm.
 * User: Thans
 * Date: 2018/10/17
 * Time: 13:53
 */

namespace app\common\controller;

use think\facade\App;
use think\Loader;
use think\View;

abstract class Addons extends Base
{
    private $addonsPath = '';
    private $name = '';
    private $options;

    public function __construct()
    {
        parent::__construct();
        $this->name = $this->getName();
        $path = Loader::parseName($this->name);
        $this->addonsPath = ADDONS_PATH . $path . '/';
    }

    final public function getAddonsPath()
    {
        return $this->addonsPath;
    }

    final public function getName()
    {
        if (empty($this->name)) {
            $class = get_class($this);
            $this->name = substr($class, strrpos($class, '\\') + 1);
        }
        return $this->name;
    }

    //必须实现安装
    abstract public function install();

    //必须卸载插件方法
    abstract public function uninstall();

    final function init()
    {

    }

    final function getOptions()
    {
        if (is_null($this->options)) {

            $res = \app\common\facade\Addons::getAddonsOptions($this->name);
            if ($res['code'] == 1001) {
                $this->options = $res['data'];
                return $this->options;
            }
        }
        return $this->options;
    }

    final function fetch($template = '', $vars = [], $config = [])
    {
        $new = [];
        $old = config('template.tpl_replace_string');
        $option = cmf_option('system');
        if ($option['cdn_status']) {
            $new = [
                '__ADDONS_TMPL__' => $option['cdn_url'] . '/addons/' . $this->name . '/view/',
                '__LAYUI__' => $option['cdn_url'] . $old['__LAYUI__'],
                '__STATIC__' => $option['cdn_url'] . $old['__STATIC__'],
            ];
        } else {
            $new['__ADDONS_TMPL__'] = '/addons/' . $this->name . '/view/';
        }
        $view_path = $this->addonsPath . 'view/';
        $this->view->config('view_path', $view_path);
        $this->view->config('tpl_replace_string', array_merge($old, $new));
        $template = $view_path . $template . '.html';
        return $this->view->fetch($template, $vars, $config);
    }
}